package com.blog.controller.sys.user;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.blog.common.base.BaseController;
import com.blog.common.base.ResponseReslut;
import com.blog.common.constants.Constants;
import com.blog.common.util.MD5Util;
import com.blog.entity.sys.Menu;
import com.blog.entity.sys.Role;
import com.blog.entity.sys.User;
import com.blog.entity.sys.UserAndRole;
import com.blog.service.sys.MenuService;
import com.blog.service.sys.RoleService;
import com.blog.service.sys.UserAndRoleService;
import com.blog.service.sys.UserService;
import com.blog.vo.UserRoleVo;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Controller
@RequestMapping("/user")
public class UserController extends BaseController{
	
		@Autowired
		private UserService userService;
		
		@Autowired
		private RoleService roleService;
	
		@Autowired
		private MenuService menuService;
		
		@Autowired
		private UserAndRoleService userAndRoleService;
		
		//用户登陆 
		@ResponseBody
		@PostMapping("/login")
		public ResponseReslut login(User user,HttpSession session)
		{	
			//1.验证数据
			if(StringUtils.isEmpty(user.getUsername()))
			{
				return resultError("用户名不能为空！");
			}
			if(StringUtils.isEmpty(user.getPassword()))
			{
				return resultError("密码不能为空！");
			}
			//都通过了，获得主体
			Subject subject=SecurityUtils.getSubject();
			//封装token
			UsernamePasswordToken token=new UsernamePasswordToken(user.getUsername(),
				MD5Util.MD5(user.getPassword()));
			try {
				subject.login(token);//这里进入自定义的realm里面去，如果有异常就说明 用户名 和密码 是错误的
				String userName=(String)SecurityUtils.getSubject().getPrincipal();
				ResponseReslut currentUser=this.userService.findByUserName(userName);
				if(!Constants.HTTP_RES_CODE_200.equals(currentUser.getCode()))
				{
					return currentUser;
				}
				User getUser=(User)currentUser.getData();
				//得到角色 
				Role getRole=getRoleName(session,getUser.getId());
				JSONArray menuJson=getAllMenuByPidAndRoleId(1,getRole.getId());
				//把用户放在session里面   TODO  以后放在redis里面
				session.setAttribute("currentUser",getUser);
				session.setAttribute("currentRole",getRole);
				session.setAttribute("currentMenu",menuJson);
				return resultSuccess("登陆成功");
			
			} catch (Exception e) {
				return resultError("登陆失败！用户名和密码错误！");
			}
			
		}
		
		//得到用户的角色    TODO  目前只做了 一个用户只有一种角色 后期 一个用户多种角色
		public Role  getRoleName(HttpSession session,Integer userId)
		{
			//查询用户角色
			List<Role> roleList=roleService.listRole(userId);
			return roleList.get(0);
		}
		
		

		//根据父节点   查询一层数据的菜单
		public JSONArray  getOneMenuByParentId(int parentId,int roleId){
			List<Menu> menuList=menuService.listMenuRole(parentId,roleId);
			JSONArray   jsonArray=new JSONArray();
			for(Menu menu : menuList)//把集合变成json
			{
				JSONObject jb=new JSONObject();
				jb.put("id", menu.getId());//菜单id
				jb.put("pid", menu.getParentId());//pid
				jb.put("name",menu.getName());//菜单名称
				jb.put("icon", menu.getIcon());//图标
				jb.put("url",menu.getUrl()); //地址
				jb.put("leaf",menu.getLeaf()); //地址
				jsonArray.add(jb);
			}
			return jsonArray;
		}

		
		//根据pid   和   roleId  查询菜单 递归
		public JSONArray getAllMenuByPidAndRoleId(int parentId,int roleId)
		{
			JSONArray jsonMuenList=this.getOneMenuByParentId(parentId,roleId);//json遍历
			for(int i=0;i<jsonMuenList.size();i++)
			{
				JSONObject jsonMuenObject=(JSONObject) jsonMuenList.get(i);
				//如果是子节点   跳出循环
				if(1==jsonMuenObject.getInteger("leaf"))
				{
					//如果是叶子节点 就给jsonMuenObject 添加一个chliend属性  拼接
					//然后自己调用自己
					int menuId=jsonMuenObject.getInteger("id");
					//把结果封装到jsonMuenList 里面去
					jsonMuenObject.put("children", getAllMenuByPidAndRoleId(menuId,roleId));
				}else
				{
					continue;
				}
			}
			return jsonMuenList;
		}

		
		/**************************************************************/
		
		@ResponseBody
		@PostMapping("/userList")
		public Map<String,Object>  userList(int pageNumber,int pageSize,String username,String phone)
		{
			Map<String,Object> mapParam=new HashMap<>();
			mapParam.put("pageNumber", (pageNumber-1)*pageSize);
			mapParam.put("pageSize", pageSize);
			mapParam.put("username", username);
			mapParam.put("phone", phone);
			List<User> listUser=userService.listUser(mapParam);
			for(User u : listUser)
			{
				 
				List<Role> listRole=roleService.listRole(u.getId());
				StringBuffer sb=new StringBuffer();
				for(Role r : listRole)
				{
					sb.append(","+r.getName());
				}
				//把第一个 ，变为空
				u.setRoles(sb.toString().replaceFirst(",",""));
			}
			Integer total=userService.countUser(mapParam);
			Map<String,Object> map=new HashMap<>();
			map.put("rows", listUser);
			map.put("total", total);
			return map;
		}

		
		
		/**
		 * 
		 * @author: chb
		 * @date: 2018年7月6日 下午3:16:07
		 * @param user
		 * @param reqest
		 * @return 
		 * 作用：   用户添加
		 */
		@ResponseBody
		@RequestMapping(value = "/save", method = RequestMethod.POST)
		public ResponseReslut saveUser(UserRoleVo vo)
	    {
			if(vo.getDeptId()==null)
			{
				return resultError("请给用户分配权限！");
			}
			User u=new User();
		    BeanUtils.copyProperties(vo,u);
			ResponseReslut result=userService.saveUser(u);
			//添加用户角色关联表中
			if(result.getCode()==200)
			{
				UserAndRole ur=new UserAndRole();
				ur.setUser_id(u.getId());
				ur.setRole_id(vo.getDeptId());
				userAndRoleService.insertUserRole(ur);
			}
			return result;
	    }  
		
		/**
		 * 
		 * @author: chb
		 * @date: 2018年7月12日 上午11:27:15
		 * @param list
		 * @param userIds
		 * @return
		 * 作用：用户删除
		 */
		@ResponseBody
		@RequestMapping(value = "/delects", method = RequestMethod.POST)
		public ResponseReslut delects(@RequestParam("usersList") String list,String userIds)
		{
			  
			//只是为了测试解析json  没用 
			JSONArray jsonArray = JSONArray.parseArray(list);//变为 json数组 
			List<Map<String,Object>> mapListJson = (List)jsonArray;//使用Map<String,Object> 接受  不确定对象  方便
			for(int i=0;i<mapListJson.size();i++)
			{
	            Map<String,Object> obj=mapListJson.get(i);
	            for(Entry<String, Object> entry : obj.entrySet()){
	                String strkey1 = entry.getKey();
	                Object strval1 = entry.getValue();
	                if ("0".equals(strkey1)) {  //0表示没有 key 
						
					}else{
						System.out.println("KEY:"+strkey1+"  -->  Value:"+strval1+"\n");
					}
	                
	            }
			}
			/***************************/
			//删除用户开始
			//1.首先要删除 角色和用户的关联表 
			//2.在删除用户
			//3.删除其他信息 相关信息  一般软删除
			if(StringUtils.isNotEmpty(userIds))
			{
				String userId[]=userIds.split(","); 
				try {
					for(String id:userId)
					{
						roleService.delectUserAndRole(Integer.parseInt(id));
						userService.deleteUsers(Integer.parseInt(id));
					}
				return setResultSuccess("删除成功");
				
				} catch (Exception e) {
					return resultError("删除失败");
				}
			}
			
			return resultError("删除失败");
		}
		
		//用户修改
		@GetMapping("/edit/{id}")
		public String edit(Model model, @PathVariable("id") Integer id) {
			
			User user=userService.getUser(id);
			List<Role> roles=roleService.selectRoleByUserId(id);
			StringBuffer sb=new StringBuffer();
			for(Role role : roles)
			{
				sb.append(","+role.getName());
			}
			user.setRoles(sb.toString().replaceFirst(",",""));
			model.addAttribute("user", user);
			return "sys/role/edit";
		}

		//用户修改
		@ResponseBody
		@PostMapping("/update")
		public ResponseReslut updateUser(UserRoleVo vo,HttpSession session)
		{
			
	 
			if(vo.getId()==null)
			{
				return resultError("请选择要修改的用户！");
			}
			if(StringUtils.isNotEmpty(vo.getUsername().trim()))
			{
				String name=userService.selectUserName(vo.getUsername().trim());
				if(vo.getUsername().trim().equals(name))
				{
					return resultError("用户名已经存在!");
				}
			}
			User u=new User();
		    BeanUtils.copyProperties(vo,u);
		    Integer row=0;//修改状态
		    if(StringUtils.isNotEmpty(vo.getUsername().trim()) || StringUtils.isNotEmpty(vo.getPhone().trim()) || StringUtils.isNotEmpty(vo.getEmail().trim()))
		    {
		    	  row=userService.update(u);
		    } 
			if(vo.getDeptId()!=null)
			{
				UserAndRole ur=new UserAndRole();
				ur.setUser_id(vo.getId());
				ur.setRole_id(vo.getDeptId());
				userAndRoleService.deleteUserRole(ur);
			 row=userAndRoleService.insertUserRole(ur);
				
			}
			//添加用户角色关联表中
			if(row>0)
			{
				return setResultSuccess("修改成功!");
			}
			return resultError("你没有输入要修改的内容！");
		}

		
		@ResponseBody
		@PostMapping("/updatePwd")
		public ResponseReslut updatePwd(Integer userIdPwd,String restPassword)
		{
			User u=new User();
			u.setId(userIdPwd);
			u.setPassword(MD5Util.MD5(restPassword));
			Integer row=userService.update(u);
			if(row>0)
			{
				return setResultSuccess("修改成功!");
			}
			return resultError("修改失败！");
		}
		
		@ResponseBody
		@GetMapping("/remove/{id}")
		public ResponseReslut remove(@PathVariable("id") Integer id)
		{
			UserAndRole ur=new UserAndRole();
			ur.setUser_id(id);
			userAndRoleService.deleteUserRole(ur);
			Integer row=userService.deleteUser(id);
			if(row>0)
			{
				return setResultSuccess("删除成功!");
			}
			return resultError("删除失败！");
		}
		
		
}
